package com.zsrt.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {

	public  LoginFilter(){
		System.out.println("构造方法...");
		
	}
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("init...");
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest  request  = (HttpServletRequest) req;
		HttpServletResponse response  = (HttpServletResponse) res;
		
		//看session中有没有用户信息
		
		//1 拿到session
		HttpSession session = request.getSession();
		
		//? 对   /user /register.jsp 路径需要放过  为什么 因为 register.jsp  user 里面 肯定没有用户信息
		
		//?
		
		String uri  = request.getRequestURI();
		
		
		System.out.println(uri);
		
		//2 看用户信息是否为空
		Object user = session.getAttribute("user");
		
		if(null == user){
			
			//说明用户没有登录 
			
			if(uri.contains("user") || uri.contains("login.jsp")|| uri.contains("cookie.jsp") || uri.contains("success.jsp")  ||uri.contains("register")|| uri.contains("counter")){
				//放过1中特殊的情况  用户正在登录的那个方法  还有一个页面也要放行   register.jsp
				chain.doFilter(request, response);
				return;
			}


			// 说明没有登录
			request.getRequestDispatcher("login.jsp").forward(request, response);
			
		}else{
			
			//放行
			chain.doFilter(request, response);
			//request.getRequestDispatcher("success.jsp").forward(request, response);
		}
				
		/*if(uri.contains("user") || uri.contains("register.jsp") || uri.contains("success.jsp")){
			chain.doFilter(request, response);
		}*/
		
		
		
	}

	@Override
	public void destroy() {
		System.out.println("destroy...");
	}

}
